﻿#region Copyright and License
/*==============================================================================
 *  Copyright (c) cndotnet.org Corporation.  All rights reserved.
 * ===============================================================================
 * This code and information is provided "as is" without warranty of any kind,
 * either expressed or implied, including but not limited to the implied warranties
 * of merchantability and fitness for a particular purpose.
 * ===============================================================================
 * Licensed under the GNU General Public License (GPL) v2
 * http://www.cndotnet.org/ezsocio
 * ==============================================================================*/
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.Web.UI;
using CNdotnet.Ezsocio.BusinessObjects;
using CNdotnet.Ezsocio.BusinessServices;
using CNdotnet.Ezsocio.Core.Web;
using CNdotnet.Ezsocio.Core.Service;
using CNdotnet.Ezsocio.BusinessInterfaces;

namespace CNdotnet.Ezsocio.Controllers
{
    [HandleError]
    [OutputCache(Location = OutputCacheLocation.None)]
    public class AccountController : BaseController
    {
        private AccountService service = new AccountService();

        public ActionResult Login()
        {
            ViewData["Title"] = "登录";
            return View();
        }

        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Login(string email, string password, bool? rememberMe)
        {
            AccountContract account = new AccountContract();
            UpdateModel(account, new[] { "Email", "Password" });

            //if (!Validat<AccountContract>(account))
            //{
            //    return View("Login", account);
            //}

            if (!ControllerContext.HttpContext.User.Identity.IsAuthenticated)
            {
                MembershipStatus loginSuccessful = service.ValidateUser(email, password);

                ViewData["MsgInfo"] = string.Empty;

                switch (loginSuccessful)
                {
                    case MembershipStatus.Success:
                        FormsAuthentication.SetAuthCookie(email, rememberMe ?? false);
                        ContextService.Current.User = service.GetAccountByEmail(email,true);
                        service.UpdateOnlie(ContextService.Current.User.ID, true);
                        Initialize();
                        return RedirectToAction("Index", "Home");                        
                    case MembershipStatus.Locked:
                        ViewData["MsgInfo"] = "当前用户已经锁定";
                        break;
                    case MembershipStatus.NotVerified:
                        ViewData["MsgInfo"] = "当前用户未验证";
                        break;
                    case MembershipStatus.Failed:
                        ViewData["MsgInfo"] = "登陆失败！";
                        break;
                }
            }

            return View();
        }

        private void Initialize()
        {
            AppContract app = new AppContract();
            app.ModuleContracts = LoadService<IModuleService>().GetModulesByUserId(ContextService.Current.User.ID);
            ContextService.Current.App = app;
        }

        /// <summary>
        /// Create a new user
        /// </summary>
        /// <returns></returns>
        public ActionResult Register()
        {
            ViewData["Title"] = "注册";
            // not submit
            if (Request.HttpMethod != "POST")
            {
                return View();
            }
            AccountContract account = new AccountContract();
            UpdateModel(account, new[] { "Email", "TrueName", "Password", "PassConfirm" });

            // validate contract
            if (!Validat<AccountContract>(account))
            {
                return View("Register", account);
            }

            IAccountService service = LoadService<IAccountService>();
            if (service.Exist(account.Email))
            {
                ViewData.ModelState.AddModelError("Email", "该Email地址已经被注册，请重新输入");
                //ViewData.ModelState.AddModelError("Email", account.Email, "该Email地址已经被注册，请重新输入");
                return View();
            }
            if (service.Register(account))
            {
                ViewData["IsSucess"] = true;
            }
            return View("Register");
        }

        /// <summary>
        /// used for jQuery validation remote method
        /// </summary>
        /// <param name="email">Email address</param>
        /// <returns></returns>
        public JsonResult IsEmailAvailable(string email)
        {
            JsonResult result = new JsonResult();
            result.Data = !service.Exist(email);
            return result;
        }

        /// <summary>
        /// used for get user's avaliable by jQuery validation remote method
        /// </summary>
        /// <param name="email">Email address</param>
        /// <returns></returns>
        public JsonResult IsEmailNotAvailable(string email)
        {
            JsonResult result = new JsonResult();
            result.Data = service.Exist(email);

            return result;
        }

        /// <summary>
        /// used for validating password by jQuery validation remote method
        /// </summary>
        /// <param name="currentPassword">Current Password</param>
        /// <returns></returns>
        public JsonResult IsValidatePassword(string currentPassword)
        {
            JsonResult result = new JsonResult();
            result.Data = service.ValidatePassword(currentPassword);

            return result;
        }

        public ActionResult RegVerify()
        {
            ViewData["Title"] = "验证邮箱";
            return View();
        }

        public ActionResult Logout()
        {            
            ContextService.Close();
            FormsAuthentication.SignOut();
            return RedirectToAction("Index", "Home");
        }

        public ActionResult ChangePassword(string currentPassword, string newPassword, string confirmPassword)
        {
            ViewData["Title"] = "修改密码";

            if (ContextService.Current.User == null)
            {
                return RedirectToAction("Index", "Home");
            }

            if (ControllerContext.HttpContext.User.Identity.IsAuthenticated)
            {
                if (Request.HttpMethod != "POST")
                {
                    return View();
                }

                //TODO: check the password input validation
                //TODO: check the newPassword & confirmPassword are same

                if (service.ValidatePassword(currentPassword))
                {
                    if (service.ChangePassword(currentPassword, newPassword))
                    {
                        ViewData["MsgInfo"] = "密码修改成功。";
                    }
                    else
                    {
                        //TODO: Change password failed.
                        return View();
                    }
                }
            }

            return View();
        }

        public ActionResult ResetPassword(string email)
        {
            ViewData["Title"] = "忘记密码 － 重置密码";

            //TODO: Change the logic of reset password.

            ViewData["MsgInfo"] = string.Empty;

            if (!ControllerContext.HttpContext.User.Identity.IsAuthenticated)
            {
                if (Request.HttpMethod != "POST")
                {
                    return View();
                }

                if (string.IsNullOrEmpty(email))
                {
                    //ViewData.ModelState.AddModelError("Email", email, "Email不能为空");
                    ViewData["MsgInfo"] = "Email不能为空。";
                    return View();
                }

                if (service.ResetPassword(email))
                {
                    ViewData["MsgInfo"] = "我们已经把密码发送到你的邮箱" + email + "中, 请检查您的邮箱。";
                }
                else
                {
                    ViewData["MsgInfo"] = "用户验证失败，请重新选择合法Email。";
                }
            }

            return View();
        }

        #region Logo
        public ActionResult Logo() {
            ViewData["Title"] = "头像设置";
            ViewData["User"] = ContextService.Current.User;
            return View();
        }

        public string UploadLogo() {
            var file = HttpContext.Request.Files[0];
            var stream = file.InputStream;
            string fileName = System.IO.Path.GetFileName(file.FileName);
            string virtualPath = "/Content/Images/Uploads/" + fileName;
            string savePath = HttpContext.Server.MapPath(virtualPath);
            Image img = Image.FromStream(stream);
            img.Save(savePath);
            service.UpdateUserLogo(ContextService.Current.User.ID, virtualPath);
            ContextService.Current.User.LogoUrl = virtualPath;
            return "{error:'',msg:'success',fileName:'"+virtualPath+"'}";
        }
        #endregion

        #region Profile
        [AcceptVerbs("GET"), ActionName("Profile")]
        public ActionResult Profile() {
            ViewData["Title"] = "基本资料设置";
            var user = ContextService.Current.User;
            ViewData["User"] = user;
            List<int> years = new List<int>();
            for (int i = 0; i < 31; i++) {
                years.Add(DateTime.Now.AddYears(-30 + i).Year);
            }
            object sel = null;
            if (user.Birthday.HasValue) {
                sel = user.Birthday.Value.Year;
            }
            SelectList yearsList = new SelectList(years, sel);            
            ViewData["Year"] = yearsList;
            List<int> months = new List<int>();
            for (int i = 1; i <= 12; i++) {
                months.Add(i);
            }
            if (user.Birthday.HasValue) {
                sel = user.Birthday.Value.Month;
            }
            SelectList monthList = new SelectList(months, sel);           
            ViewData["Month"] = monthList;
            List<int> days = new List<int>();
            for (int i = 1; i <= 31; i++) {
                days.Add(i);
            }
            if (user.Birthday.HasValue) {
                sel = user.Birthday.Value.Day;
            }
            SelectList dayList = new SelectList(days, sel);            
            ViewData["Day"] = dayList;
            return View();
        }
        [AcceptVerbs("POST"), ActionName("Profile")]
        public void UpdateProfile() {
            var user = ContextService.Current.User;
            UpdateModel(user, new[] { "NickName", "Hometown", "QQ", "MSN", "PhoneNumber","Website"});
            var rq = HttpContext.Request;
            DateTime birthDay = Convert.ToDateTime(rq["Year"] + "-" + rq["Month"] + "-" + rq["Day"]);
            user.Birthday = birthDay;
            service.UpdateProfile(user);
            Response.Redirect("/");
        }
        #endregion
    }
}
